import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 98152
 * Date: 2024-11-03
 * Time: 11:12
 */
class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
public class Test2 {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int size1 = size(pHead1);
        int size2 = size(pHead2);
        ListNode cur1 = pHead1;
        ListNode cur2 = pHead2;
        int dif = size1 - size2;
        if (dif > 0) {
            while (dif-- != 0) {
                cur1 = cur1.next;
            }
        } else {
            while (dif++ != 0) {
                cur2 = cur2.next;
            }
        }
        ListNode intersection = null;
        while (cur1 != null && cur2 != null) {
            if (cur1 == cur2) {
                intersection = cur1;
                break;
            }
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return intersection;
    }

    private int size(ListNode pHead) {
        int size = 0;
        ListNode cur = pHead;
        while (cur != null) {
            cur = cur.next;
            size++;
        }
        return size;
    }
}
